package com.recipe.service.impl;

import com.alibaba.fastjson.JSON;
import com.recipe.common.config.RedisUtil;
import com.recipe.entity.vo.BasketVo;
import com.recipe.entity.vo.SourceVo;
import com.recipe.service.BasketService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lzk
 * @date 2024-06-26 09:58:27
 * @description
 */
@Service("basketService")
@RequiredArgsConstructor
public class BasKetServiceImpl implements BasketService {

    private static final String BASKET_KEY = "basket";

    private final RedisUtil redisUtil;
    @Override
    public Boolean add(BasketVo basketVo) {
        List<SourceVo> sourceVos = basketVo.getSourceVos();
        redisUtil.putHash(BASKET_KEY, basketVo.getName(), JSON.toJSONString(sourceVos));

        return null;
    }

    @Override
    public Boolean delete(String name) {
      return   redisUtil.deleteHashField(BASKET_KEY, name);

    }

    @Override
    public Boolean deleteAll() {
       redisUtil.getHashAndDelete(BASKET_KEY);

       return true;
    }

    @Override
    public List<BasketVo> getAll() {
        Map<Object, Object> hash = redisUtil.getHash(BASKET_KEY);
        List<BasketVo> basketVos=new ArrayList<>();

       hash.forEach((k,v)->{
           BasketVo basketVo=new BasketVo();
           basketVo.setName(k.toString());
           List<SourceVo> sourceVos = JSON.parseArray(v.toString(), SourceVo.class);
           basketVo.setSourceVos(sourceVos);
           basketVos.add(basketVo);


       });

        return basketVos;
    }


}
